package com.minivision.fdiot.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.minivision.fdiot.common.RestResult;
import com.minivision.fdiot.util.ParamUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 用于记录API调用时间的切面
 * @author hughzhao
 * @2017年5月22日
 */
@Aspect
@Component
@Slf4j
public class TimeUsedRecorder {

  @Autowired
  private ObjectMapper om;

  @Around("within(@org.springframework.web.bind.annotation.RestController *)")
  public Object timeuse(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    String url = request.getRequestURL().toString();
    String paramString = ParamUtils.getParamString(request);
    //记录API请求日志
    log.info("{}---->{}", url, paramString);

    long start = System.currentTimeMillis();
    try{
      Object obj = proceedingJoinPoint.proceed();
      if (obj instanceof RestResult<?>) {
        RestResult<?> res = (RestResult<?>) obj;
        //调用时间
        res.setTimeUsed((int) (System.currentTimeMillis() - start));
        log.info("Normal rest result: {}", om.writeValueAsString(res));
      } else {
        log.warn("Unexpected result: {}", obj);
      }
      return obj;
    }catch (Throwable t){
      log.error("Api Error", t);
      throw t;
    }
  }

}
